package cn.itcast.service.impl;

import cn.itcast.dao.StudentDao;
import cn.itcast.domain.Student;
import cn.itcast.service.StudentService;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.util.List;

public class StudentServiceImpl implements StudentService {
    @Override
    public List<Student> findAll() throws Exception {
        SqlSession sqlSession = new SqlSessionFactoryBuilder().build(Resources.getResourceAsStream("mybatis-config.xml")).openSession();

        StudentDao studentDao = sqlSession.getMapper(StudentDao.class);
        List<Student> students = studentDao.findAll();

        sqlSession.close();
        return students;
    }

    @Override
    public void delete(String id) throws Exception {
        SqlSession sqlSession = new SqlSessionFactoryBuilder().build(Resources.getResourceAsStream("mybatis-config.xml")).openSession(true);
        StudentDao mapper = sqlSession.getMapper(StudentDao.class);
        Integer i1 = Integer.parseInt(id);
        mapper.deleteById(i1);
        sqlSession.close();
    }

    @Override
    public void update(Student stu) throws Exception {
        SqlSession sqlSession = new SqlSessionFactoryBuilder().build(Resources.getResourceAsStream("mybatis-config.xml")).openSession(true);
        StudentDao mapper = sqlSession.getMapper(StudentDao.class);
        mapper.upadteById(stu);
        sqlSession.close();
    }

    @Override
    public void addStudent(Student stu) throws Exception {
        SqlSession sqlSession = new SqlSessionFactoryBuilder().build(Resources.getResourceAsStream("mybatis-config.xml")).openSession(true);
        StudentDao mapper = sqlSession.getMapper(StudentDao.class);
        mapper.addStudent(stu);
        sqlSession.close();
    }


}
